package com.xdf.conf;

import de.codecentric.boot.admin.server.config.AdminServerProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;

/**
 * @author chanchaw
 * @create 2025-08-18 15:34
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    // 应用名称 = bootstrap.yml # server.context-path
    // 即配置文件中设置的应用名称：/ecomm-admin
    private final String adminContextPath;
    public SecurityConfig(AdminServerProperties properties){
        this.adminContextPath = properties.getContextPath();
    }

    // 本模块要通过 SpringSecurity 登录
    // 本方法做认证方面的配置
    @Override
    protected void configure(HttpSecurity http) throws Exception{
        SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
        successHandler.setTargetUrlParameter("redirectTo");
        successHandler.setDefaultTargetUrl(adminContextPath + "/");

        // 设置请求路径权限
        http.authorizeRequests()
                // 1. 所有静态资源和登录页面不需要权限
                .antMatchers(adminContextPath + "/assets/**").permitAll()
                .antMatchers(adminContextPath + "/login").permitAll()
                // 2. 其他请求需要认证
                .anyRequest().authenticated()
                // 3. 登录页面
                .and().formLogin().loginPage(adminContextPath + "/login").successHandler(successHandler)
                // 4. 注销请求
                .and().logout().logoutUrl(adminContextPath + "/logout")
                // 5. 开启 http basic 支持，其他微服务注册时需要使用
                .and().httpBasic()
                // 6. 开启基于 cookie 的 CSRF 保护
                .and().csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                // 7. 忽略下面路径的 CSRF 保护，以便其他微服务可以实现注册
                .ignoringAntMatchers(adminContextPath + "/instances", adminContextPath + "/actuator/**");
    }
}
